using UnityEngine;
using System.Collections;
[RequireComponent (typeof (Rigidbody))]
public class CharacterMovement : MonoBehaviour {

	Vector3 velocityDirection;
	public float speed = 50;
	public float movementDrag = 10;
	public float stoppedDrag = 200;
	public float acceleration = 0.9f;
	GameObject torso;
	GameObject legs;
	Vector3 walkRot = Vector2.zero;
	Camera mainCam;
	void Start () {
		GetComponent<Rigidbody>().mass = 0.01f;
		torso = transform.Find ("Torso").gameObject;
		legs = transform.Find ("Legs").gameObject;
		mainCam = transform.Find ("Main Camera").GetComponent<Camera>();
	}
	// Update is called once per frame
	void FixedUpdate () {
		Walking ();
		Looking ();
	}

	void Walking () {
		velocityDirection.x = Input.GetAxis("Horizontal");
		velocityDirection.z = Input.GetAxis("Vertical");
		if (velocityDirection.magnitude != 0 && GetComponent<Rigidbody>().velocity.magnitude < speed) {
			GetComponent<Rigidbody>().AddForce (velocityDirection.normalized * acceleration * (1f - Mathf.Pow((GetComponent<Rigidbody>().velocity.magnitude/speed), 2)));
			GetComponent<Rigidbody>().drag = movementDrag;
			walkRot = Vector3.Lerp (walkRot, GetComponent<Rigidbody>().velocity, 0.1f);
			legs.GetComponent<Animator>().enabled = true;
		} else {
			GetComponent<Rigidbody>().drag = stoppedDrag;
			legs.GetComponent<Animator>().enabled = false;
		}

		if (walkRot.magnitude > 0.1f) {
			legs.transform.rotation = Quaternion.LookRotation( new Vector3(0,-1,0), new Vector3(walkRot.x, 0, walkRot.z));
		}
		GetComponent<Rigidbody>().velocity = Vector3.ClampMagnitude (GetComponent<Rigidbody>().velocity, speed);
	}
	void Looking () {
		Vector3 lookVector = mainCam.ScreenToWorldPoint(Input.mousePosition);
		lookVector.y = 0;
		torso.transform.rotation = Quaternion.LookRotation(new Vector3(0,-1,0),transform.position - lookVector);
	}
}
